package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document read = reader.read(in);
        Element root = read.getRootElement();
        String namespace = root.attributeValue("namespace");
        // 在root下找到4种标签
        List<String> sqlTypeList = Arrays.asList("select", "update", "insert", "delete");
        // 获取所有sql标签
        List<Element> elements = this.getElementsFromRoot(root, sqlTypeList);
        // 构造MappedStatement对象
        this.buildStatement(elements, namespace);
    }

    /**
     * 获取根目录下所有的sql标签
     */
    public List<Element> getElementsFromRoot(Element root, List<String> list) {
        List<Element> elements = new ArrayList<>();
        for (String sqlType : list) {
            if (sqlType == null || sqlType.length() == 0) {
                continue;
            }
            String node = "//" + sqlType;
            List<Element> nodes = root.selectNodes(node);
            elements.addAll(nodes);
        }
        return elements;
    }

    /**
     * 根据elements构建MappedStatement
     */
    public void buildStatement(List<Element> elements, String namespace) {
        Map<String, MappedStatement> map = configuration.getMap();
        for (Element element1 : elements) {
            MappedStatement mappedStatement = new MappedStatement();
            String id = element1.attributeValue("id");
            String s = namespace + "." + id;
            mappedStatement.setId(s);
            String resultType = element1.attributeValue("resultType");
            mappedStatement.setResultType(resultType);
            String parameterType = element1.attributeValue("parameterType");
            mappedStatement.setParameterType(parameterType);
            String sql = element1.getTextTrim();
            mappedStatement.setSql(sql);
            // 标签名<select> <update> <delete> <insert>
            mappedStatement.setType(element1.getQualifiedName());
            map.put(s, mappedStatement);
        }
    }


}
